﻿"use strict"

let choice = document.querySelectorAll(".choice"),
  tip = document.querySelector(".tip"),
  tipImg = document.querySelector(".tip img"),
  oForm = document.querySelector(".oForm"),
  content = document.querySelector(".search-content"), //搜索框
  keyword = document.querySelector(".keywords"),
  headline = document.querySelector(".headline"),
  backHome = document.querySelector(".backhome"),
  bookmark = document.querySelectorAll(".bookmark");

let diy_btn = document.querySelector(".diy"),
  upbk = document.querySelector(".upbk"),
  wp = document.querySelector('.wp'),
  assure = document.querySelector('.assure'),
  cancel = document.querySelector('.cancel');

let wallpaper = localStorage.wallpaper;


// Tip:增加或者删除搜索引擎，要记得更改choose函数体内link的判断条件
for (let i = 0, len = choice.length; i < len; i++) {
  choice[i].addEventListener("click", choose);
}

function choose(e) {
  e = e || window.event;
  var target = e.target; //目标统一为button元素节点！
  if (target.nodeName.toLowerCase() == "button") {
    console.log("shit!用什么火狐浏览器啊！兼容烦死了！");
  } else {
    console.log("bisoo!你是用chrome内核或者IE的呀！");
    target = target.parentNode;
  }
  var imgIndex = target.firstChild; //图片索引
  var link = target.getAttribute("data-index");
  tipImg.src = imgIndex.src; //切换为选定的搜索图标
  tip.setAttribute("data-state", link); //将搜索引擎设置为选定的引擎
  if (link == 0) {
    oForm.action = "http://www.baidu.com/s";
    content.name = "wd";
  } else if (link == 1) {
    oForm.action = "https://www.so.com/s";
    content.name = "q";
  } else if (link == 2) {
    oForm.action = "https://cn.bing.com/search";
    content.name = "q";
  } else if (link == 3) {
    oForm.action = "http://www.sogou.com/web";
    content.name = "query";
  } else {
    oForm.action = "https://www.dogedoge.com/results";
    content.name = "q";
  }
}

content.addEventListener("keyup", show);

function show() {
  var val = this.value;
  keyword.style.display = "block";

  //删除其他多余script标签的函数
  var already_Script = document.getElementsByTagName("script");
  for (let i = 0, len = already_Script.length; i < len; i++) {
    var script_index = already_Script[i].getAttribute("data-index");
    if (script_index != 0) {
      document.body.removeChild(already_Script[i]);
    }
  }


  var oScript = document.createElement("script");
  oScript.setAttribute("data-index", 1);
  var check = tip.getAttribute("data-state"); //获取当前搜索引擎的类别 
  if (check == 1) {
    oScript.src = "https://sug.so.360.cn/suggest?callback=lzw&encodein=utf-8&encodeout=utf-8&word=" + val + "";
    document.body.appendChild(oScript);
  } else {
    oScript.src = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=" + val + "&cb=lzw";
    document.body.appendChild(oScript);
  }
}

function lzw(data) {
  var key = data.s;
  var siteObj = {
    baidu: "http://www.baidu.com/s?wd=",
    qihu: "https://www.so.com/s?q=",
    bing: "https://cn.bing.com/search?q=",
    sogou: "http://www.sogou.com/web?query=",
    lookao: "https://lookao.com/search?q=",
    dogedog: "https://www.dogedoge.com/results?q="
  };
  document.querySelector(".keywords ul").innerText = " ";
  if (key.length) {
    key.forEach(function (content) {
      var oLi = document.createElement("li");
      var check = tip.getAttribute("data-state");
      oLi.innerText = content;
      if (check == 0) {
        oLi.onclick = function () {
          window.location.href = siteObj.baidu + content;
        }
      } else if (check == 1) {
        oLi.onclick = function () {
          window.location.href = siteObj.qihu + content;
        }
      } else if (check == 2) {
        oLi.onclick = function () {
          window.location.href = siteObj.bing + content;
        }
      } else if (check == 3) {
        oLi.onclick = function () {
          window.location.href = siteObj.sogou + content;
        }
      } else if (check == 4) {
        oLi.onclick = function () {
          window.location.href = siteObj.lookao + content;
        }
      } else {
        oLi.onclick = function () {
          window.location.href = siteObj.dogedog + content;
        }
      }
      document.querySelector(".keywords ul").appendChild(oLi);
    });
  } else {
    keyword.style.display = "none";
  }
}



window.onload =  function () {
  let bd = document.getElementsByTagName('body')[0];
  logo();
  rightMenu();
  bd.style.background = `url(${wallpaper}) 0 0 / cover`;
  
  headline.addEventListener("click", function () {
    aboutside("slide", 300, -300);
  });
  backHome.addEventListener("click", function () {
    aboutside("hideslide", 0, 0);
  });
  diy_btn.addEventListener("click", function () {
    showMyWindow(1, ".diybox");
    // diy(diytoggle);
  });
  upbk.addEventListener('click', (e) => {
    window.location.href = '/updatebk';
  });
  wp.addEventListener('click', (e) => {
    let url = window.prompt('请输入壁纸链接：', '/public/images/wallpapers/005.jpg');
    if (url) {
      wallpaper = url;
      bd.style.background = `url(${url}) 0 0 / cover`;
    }
  });
  assure.addEventListener('click', (e) => {
    if(window.confirm('保存？')) {
      localStorage.wallpaper = wallpaper;
    }
    showMyWindow(0, ".diybox");
  });
  cancel.addEventListener('click', (e) => {
    showMyWindow(0, '.diybox');
  })

  // let mask = document.getElementsByClassName('pagemask')[0];
  // setTimeout(() => {
  //   mask.style.opacity = 0;
  //   setTimeout(() => {
  //     mask.style.display = 'none';
  //   }, 100);
  // }, 1500);
};





// -----------------------------------------------------------------------------------
/**
 * @description logo load
 */
function logo() {
  var num = function (a, b) {
    return Math.floor(a + Math.random() * (b - a));
  }
  var logo = document.querySelector(".hpic"),
    wPath = "/public/images/logo/" + num(1, 7) + ".png";
  logo.src = wPath;
}

/**
 * @description contextmenu
 */
function rightMenu() {
  var rm = document.querySelector(".rightMenu");

  document.onclick = function (e) {
    rm.style.display = "none";
  }
  document.oncontextmenu = function (e) {
    e = e || window.event;

    var flag = judgePath(e.target, "rside") || judgePath(e.target, "diybox");

    var mx = e.clientX;
    var my = e.clientY;
    var rmWidth = rm.offsetWidth;
    var rmHeight = rm.offsetHeight;
    var pageWidth = document.documentElement.clientWidth;
    var pageHeight = document.documentElement.clientHeight;
    if (!flag) {
      if (mx + rmWidth <= pageWidth && my + rmHeight <= pageHeight) {
        rm.style.left = mx + "px";
        rm.style.top = my + "px";
      } else if (my + rmHeight > pageHeight) { //点击位置偏向下边
        if (mx + rmWidth <= pageWidth) {
          rm.style.top = (my - rmHeight) + "px";
          rm.style.left = mx + "px";
        } else { //且偏向右边
          rm.style.top = (my - rmHeight) + "px";
          rm.style.left = (mx - rmWidth) + "px";
        }
      } else {
        rm.style.left = (mx - rmWidth) + "px";
        rm.style.top = my + "px";
      }

      rm.style.display = "block";
    }
    return false;
  }
}

/**
 * @description whether exits the particular element in this event path.
 * @param {Element} cur The Element you wanna judge
 * @param {String} classname The particular element's classname 
 */
function judgePath(cur, classname) {
  while (cur != null && cur.className != classname)
    cur = cur.parentElement;
  if (!cur)
    return false;
  else
    return true;
}

/**
 * @description control the particular element to run an animation
 * @param {number} setting 1 or other
 * @param {string} name animate target
 */
function showMyWindow(setting, name) {
  var d_box = document.querySelector(name);
  if (setting == 1) {
    d_box.style.display = "block";
    d_box.style.animationName = "showdiy";
  } else {
    d_box.style.display = "none";
  }
}

/**
 * @description non-reuse
 * @param {String} a animation name
 * @param {Number} b offset
 * @param {Number} c offset
 */
function aboutside(a, b, c) {
  var side = document.querySelector(".rside");
  var searchBody = document.querySelector(".search-body");
  var body = document.getElementsByTagName("body")[0];
  side.style.animationName = a;
  headline.style.right = b + "px";
  searchBody.style.right = b + "px";
  body.style.backgroundPosition = "" + c + "px 0";
}